package com.zrkj.util;

import cn.hutool.core.collection.CollUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;

import java.util.Date;
import java.util.List;


public class JwtUtil {

    /**
     * 秘钥
     */
    public static final String SECRET_KEY = "how are you?I'm fine think you ,and you? I'm fine too!";

    /**
     * token过期时间
     */
    public static final Long TOKEN_EXPIRE_TIME = 30 * 24 * 60 * 60 * 1000L;

    /**
     * 签发人
     */
    private static final String ISSUER = "www.zr-power.cn";

    /**
     * 生成签名
     *
     * @param userId
     * @return
     */
    public static String generateToken(String userId, String userName,String iotToken) {

        Date now = new Date();

        Date expired = new Date(now.getTime() + TOKEN_EXPIRE_TIME);
        /** 算法 */
        Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY);

        /** 签发人 签发时间 过期时间 保存身份标识 */
        String token =
                JWT.create()
                        .withAudience()
                        .withIssuer(ISSUER)
                        .withIssuedAt(now)
                        .withNotBefore(now)
                        .withAudience(userId.toString())
                        .withClaim("userId", userId)
                        .withClaim("userName", userName)
                        .withClaim("iotToken", iotToken)
                        .withExpiresAt(expired)
                        .sign(algorithm);
        return token;
    }

    /**
     * 验证token
     */
    public static boolean verify(String token) {
        try {
            // 算法
            Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY);
            JWTVerifier verifier = JWT.require(algorithm).withIssuer(ISSUER).build();
            verifier.verify(token);
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return false;
    }

    /**
     * 从token获取userId
     */
    public static String getUserId(String token) {
        try {

            List<String> audience = JWT.decode(token).getAudience();
            if (CollUtil.isNotEmpty(audience)) {
                return audience.get(0);
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "";
    }


    /**
     * 从token获取userId
     */
    public static String getUserName(String token) {
        try {

            Claim userNameClaim = JWT.decode(token).getClaim("userName");
            if (userNameClaim != null) {
                return userNameClaim.asString();
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "";
    }
}
